package com.weblog.upload.service;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.weblog.upload.client.UserClient;
import com.weblog.upload.config.UploadProperties;
import entity.Result;
import enums.ExceptionEnum;
import exception.MyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@EnableConfigurationProperties(UploadProperties.class)
@Slf4j
public class UploadService {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private UserClient userClient;

    @Autowired
    private HttpServletRequest request;

    /**
     * yml中的配置信息
     */
    @Autowired
    private UploadProperties uploadProperties;

    /**
     * 获取缩略图
     */
    @Autowired
    private ThumbImageConfig thumbImageConfig;

    @Autowired
    private UploadService uploadService;

    private static final Logger  LOGGER  =LoggerFactory.getLogger(UploadService.class);
    private static final List<String> ALLOW_TYPES= Arrays.asList("image/jpg","image/jpeg","image/jpg","image/png","image/bmp");

    /**
     * 上传头像（保存缩略图）
     * @param file
     * @return
     */
    public String uploadImage(MultipartFile file) {

        String originalFileName=file.getOriginalFilename();
        try {
            //校验文件类型
            String contentType = file.getContentType();
            if(!ALLOW_TYPES.contains(contentType)){
                LOGGER.info("文件内容不合法:{}",originalFileName);
                throw new MyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            //校验文件内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if(image==null){
                throw new MyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            /**
             * 先删除原来的头像
             */
            uploadService.delelteOldAvatar();
            //获取拓展名
            String extension=StringUtils.substringAfterLast(file.getOriginalFilename(),".");
            //上传到FastDFS
            StorePath storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), extension, null);

            //修改头像地址
            userClient.uploadAvatar(uploadProperties.getBaseUrl()+thumbImageConfig.getThumbImagePath(storePath.getFullPath()));
            //返回路径
            return uploadProperties.getBaseUrl()+thumbImageConfig.getThumbImagePath(storePath.getFullPath());
        } catch (IOException e) {
            //上传失败
            LOGGER.error("[文件上传]上传文件失败!",e);
            throw new MyException();
        }
     
    }

    /**
     * 异步删除旧头像
     */
    @Async(value = "delAvatar")
    void delelteOldAvatar(){

        String userId= (String) request.getAttribute("id");
        Result result = userClient.findAvatarById(userId);
        String oldAvatar = (String) result.getData();
        if(oldAvatar!=null&&!"".equals(oldAvatar)){
            //删除旧的头像地址(缩略图)
            storageClient.deleteFile(oldAvatar);
            //非缩略图地址

            String fullPath = StringUtils.substringBeforeLast(oldAvatar, "_")+"."+StringUtils.substringAfterLast(oldAvatar,".");
            storageClient.deleteFile(fullPath);
        }
    }

    /**
     * 上传文章中的多个文件
     * @param files
     */
    public List<String> uploadMultiFiles(MultipartFile[] files) {
        List<String> resultList=new ArrayList<>();
        for (MultipartFile file : files) {
            try {
                //校验文件内容
                BufferedImage image = ImageIO.read(file.getInputStream());
                if (image == null) {
                    throw new MyException(ExceptionEnum.INVALID_FILE_TYPE);
                }

                //获取拓展名
                String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
                //上传到FastDFS
                StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);

                //不加http://前端无法显示
                resultList.add("http://"+uploadProperties.getBaseUrl() + storePath.getFullPath());
                //返回路径

            } catch (IOException e) {

                //上传失败
                LOGGER.error("[文件上传]文件"+file.getOriginalFilename()+"上传失败!", e);
                throw new MyException(ExceptionEnum.UPLOAD_FILE_ERROR);

            }

        }
        return resultList;


    }

}
